const { USER_PWD_NOT_NULL, USER_NAME_EXIST } = require('../errors')
const md5 = require('../utils/md5')
const service = require('../service/user.service')
class userMiddle {
  async validity(ctx, next) {
    const { password, name } = ctx.request.body
    if (!password || !name) {
      // 用户名密码不为空
      return ctx.app.emit('error', USER_PWD_NOT_NULL, ctx)
    }
    // 用户名不能重复
    const result = await service.findByName(name)
    if (result.length > 0) {
      return ctx.app.emit('error', USER_NAME_EXIST, ctx)
    }
    await next()
  }
  // password 加密
  async md5Pwd(ctx, next) {
    const user = ctx.request.body
    let { password } = user;
    user.password = md5(password);

    await next();
  }
}
module.exports = new userMiddle();